layui.use(['form', 'layer', 'table', 'laytpl'], function () {
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        laytpl = layui.laytpl,
        table = layui.table;

    var xxx = getUrlParam('culture');

    function getUrlParam(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
        var r = window.location.search.substr(1).match(reg);  //匹配目标参数
        if (r != null) return unescape(r[2]); return null; //返回参数值
    }

    var UserID = '用户ID';
    var UserName = '用户昵称';
    var PhoneNumber = '手机号码';
    var Email = '邮箱地址';
    var Role = '所属角色';
    var Remark = '备注';
    var IsLock = '是否锁定';
    var Operation = '操作';
    var MsgConfirmBatchDelete = '确定删除选中的用户?';
    var MsgConfirmDelete = '确定删除此用户?';
    var MsgChooseNeedDelete = '请选择需要删除的用户';
    var SystemPrompt = '系统提示';
    var success = '操作成功';
    var fail = '操作失败';

    if (xxx == 'en') {
        UserID = 'User ID';
        UserName = 'User Name';
        PhoneNumber = 'Phone NUmber';
        Email = 'Email';
        Role = 'Role';
        Remark = 'Remark';
        IsLock = 'Whether the lock';
        Operation = 'Operation';
        MsgConfirmBatchDelete = 'Make sure to delete the selected user?';
        MsgConfirmDelete = 'Are you sure to delete this user?';
        MsgChooseNeedDelete = 'Please select the user you want to delete';
        SystemPrompt = 'System Prompt';
        success = 'Success';
        fail = 'Fail';
    }

    if (xxx == 'vi') {
        UserID = 'ID người dùng';
        UserName = 'tên';
        PhoneNumber = 'điện thoại';
        Email = 'Hộp thư';
        Role = 'Vai trò';
        Remark = 'Lưu ý thông tin';
        IsLock = 'khoá';
        Operation = 'Nút hoạt động';
        MsgConfirmBatchDelete = 'Xác định người dùng đã chọn đã xoá?';
        MsgConfirmDelete = 'Bạn có chắc chắn để loại bỏ?';
        MsgChooseNeedDelete = 'Hãy chọn cái cần xoá';
        SystemPrompt = 'Hệ thống gợi ý';
        success = 'Thành công';
        fail = 'Thất bại';
    }

    //用户列表
    var tableIns = table.render({
        elem: '#managerList',
        url: '/Manager/LoadData/',
        cellMinWidth: 95,
        page: true,
        height: "full-125",
        limits: [10, 15, 20, 25],
        limit: 10,
        id: "managerListTable",
        cols: [[
            { type: "checkbox", fixed: "left", width: 50 },
            //{ field: "Id", title: 'Id', width: 50, align: "center" },
            { field: 'UserName', title: UserID, minWidth: 50, align: "center" },
            { field: 'NickName', title: UserName, minWidth: 50, align: "center" },
            { field: 'Mobile', title: PhoneNumber, minWidth: 80, align: "center" },
            { field: 'Email', title: Email, minWidth: 100, align: "center" },
            { field: 'RoleName', title: Role, minWidth: 80, align: 'center' },
            { field: 'Remark', title: Remark, align: 'center' },
            { field: 'IsLock', title: IsLock, minWidth: 100, fixed: "right", align: "center", templet: '#IsLock' },
            { title: Operation, minWidth: 80, templet: '#managerListBar', fixed: "right", align: "center" }
        ]]
    });

    //搜索【此功能需要后台配合，所以暂时没有动态效果演示】
    $(".search_btn").on("click", function () {
        //if ($(".searchVal").val() !== '') {
        table.reload("managerListTable", {
            page: {
                curr: 1 //重新从第 1 页开始
            },
            where: {
                key: $(".searchVal").val()  //搜索的关键字
            }
        });
        //}
        //else {
        //    layer.msg("请输入搜索的内容");
        //}
    });

    //添加用户
    function addManager(edit) {
        var tit = "添加用户";
        if (xxx == 'vi') {
            tit = 'Thêm người dùng';
        } else if (xxx == 'en') {
            tit = 'Add User';
        }

        if (edit) {
            tit = "编辑用户";
            if (xxx == 'vi') {
                tit = 'Người dùng soạn thảo';
            } else if (xxx == 'en') {
                tit = 'Edit User';
            }
        }
        var index = layui.layer.open({
            title: tit,
            type: 2,
            anim: 1,
            area: ['500px', '95%'],
            content: "/Manager/AddOrModify?culture=" + xxx,
            success: function (layero, index) {
                var body = layui.layer.getChildFrame('body', index);
                if (edit) {
                    body.find("#Id").val(edit.Id);
                    body.find(".UserName").val(edit.UserName);
                    body.find(".NickName").val(edit.NickName);
                    body.find(".RoleId").val(edit.RoleId);
                    body.find(".Mobile").val(edit.Mobile);
                    body.find(".Email").val(edit.Email);
                    if (edit.IsLock == 1)
                        body.find("input:checkbox[name='IsLock']").prop("checked", true);
                    else
                        body.find("input:checkbox[name='IsLock']").prop("checked", false);
                    body.find(".Remark").text(edit.Remark);
                    form.render();
                }
            }
        });
    }
    $(".addManager_btn").click(function () {
        addManager();
    });

    //批量删除
    $(".delAll_btn").click(function () {
        var checkStatus = table.checkStatus('managerListTable'),
            data = checkStatus.data,
            managerId = [];
        if (data.length > 0) {
            for (var i in data) {
                managerId.push(data[i].Id);
            }
            layer.confirm(MsgConfirmBatchDelete, {
                btn: ['Yes', 'No'], //可以无限个按钮
                btn1: function (index, layero) {
                    del(managerId);
                    //按钮【按钮三】的回调
                }, title: SystemPrompt
            });
        } else {
            layer.msg(MsgChooseNeedDelete);
        }
    });

    //列表操作
    table.on('tool(managerList)', function (obj) {
        var layEvent = obj.event,
            data = obj.data;

        if (layEvent === 'edit') { //编辑
            addManager(data);
        } else if (layEvent === 'del') { //删除
            managerId = [];
            managerId.push(data.Id);
            layer.confirm(MsgConfirmDelete, {
                btn: ['Yes', 'No'], //可以无限个按钮
                btn1: function (index, layero) {
                    del(managerId);
                }, title: SystemPrompt
            });
        }
    });

    form.on('switch(IsLock)', function (data) {
        var tipText = '确定锁定当前用户吗？';

        if (xxx == 'vi') {
            tipText = 'Có chắc là khóa người dùng hiện thời không?';
        } else if (xxx == 'en') {
            tipText = 'Are you sure to lock the current user?';
        }

        if (!data.elem.checked) {
            tipText = '确定启用当前用户吗？';
            if (xxx == 'vi') {
                tipText = 'Xác định mở nó?';
            } else if (xxx == 'en') {
                tipText = 'Are you sure the current user is enabled?';
            }
        }
        layer.confirm(tipText, {
            icon: 3,
            title: SystemPrompt,
            cancel: function (index) {
                data.elem.checked = !data.elem.checked;
                form.render();
                layer.close(index);
            }
        }, function (index) {
            var checkedFlag = 0;
            if (data.elem.checked == true)
                checkedFlag = 1;
            changeLockStatus(data.value, checkedFlag);
            layer.close(index);
        }, function (index) {
            data.elem.checked = !data.elem.checked;
            form.render();
            layer.close(index);
        });
    });

    function del(managerId) {
        $.ajax({
            type: 'POST',
            url: '/Manager/Delete/',
            data: { managerId: managerId },
            dataType: "json",
            headers: {
                "X-CSRF-TOKEN-Gerald": $("input[name='AntiforgeryKey_Gerald']").val()
            },
            success: function (data) {//res为相应体,function为回调函数
                layer.msg(success, {
                    time: 2000 //20s后自动关闭
                }, function () {
                    tableIns.reload();
                    layer.close(index);
                });
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.alert(fail + XMLHttpRequest.status + "|" + XMLHttpRequest.readyState + "|" + textStatus, { icon: 5 });
            }
        });
    }

    function changeLockStatus(managerId, status) {
        $.ajax({
            type: 'POST',
            url: '/Manager/ChangeLockStatus/',
            data: { Id: managerId, Status: status },
            dataType: "json",
            headers: {
                "X-CSRF-TOKEN-Gerald": $("input[name='AntiforgeryKey_Gerald']").val()
            },
            success: function (data) {//res为相应体,function为回调函数
                layer.msg(success, {
                    time: 2000 //2s后自动关闭
                }, function () {
                    tableIns.reload();
                    layer.close(index);
                });
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.alert(fail + XMLHttpRequest.status + "|" + XMLHttpRequest.readyState + "|" + textStatus, { icon: 5 });
                tableIns.reload();
            }
        });
    }
});
